package com.wxh.cloud.gateway.filters;

import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.wxh.cloud.core.ResultDto;

import reactor.core.publisher.Mono;
/**
 * IP黑名单过滤
 * @author WXH
 *
 */
@Component
public class IPForbidGlobalFilter implements GlobalFilter, Ordered {

	private  static Logger logger = LoggerFactory.getLogger(IPForbidGlobalFilter.class);
	
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		
		String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
		
		//logger.info("============请求的IP："+ip);
		
//		if (ip.equals("127.0.0.1")) {
//			ServerHttpResponse response = exchange.getResponse();
//			ResultDto data = new ResultDto();
//				data.setCode(401);
//				data.setMessage("非法请求");
//			byte[] datas =  JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8);
//			DataBuffer buffer = response.bufferFactory().wrap(datas);
//				response.setStatusCode(HttpStatus.UNAUTHORIZED);
//				response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//			return response.writeWith(Mono.just(buffer));
//		}

		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		// TODO Auto-generated method stub
		return 0;
	}

}
